package com.aso114.project.exam;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.adapter.ExpositionAdapter;
import com.aso114.project.adapter.PicAdapter;
import com.aso114.project.base.BaseApplication;
import com.aso114.project.base.BaseFragment;
import com.aso114.project.bean.EvenBaseBean;
import com.aso114.project.bean.MsgEvent;
import com.aso114.project.bean.QuestionBaseBean;
import com.aso114.project.commonview.MyListView;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.MySharedPreferences;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by asus on 2019/1/8.
 */

public class QuestionsFragment extends BaseFragment implements ExpositionAdapter.OnItemClickListener {
    @BindView(R.id.que_img)
    ImageView queImg;
    @BindView(R.id.que_title)
    TextView queTitle;
    @BindView(R.id.que_min_title)
    TextView queMinTitle;
    @BindView(R.id.que_group)
    RadioGroup queGroup;
    @BindView(R.id.que_check_layout)
    LinearLayout queCheckLayout;
    @BindView(R.id.que_see_analysis)
    TextView queSeeAnalysis;
    @BindView(R.id.que_answer)
    TextView queAnswer;
    @BindView(R.id.que_statistics)
    TextView queStatistics;
    @BindView(R.id.que_analysis)
    TextView queAnalysis;
    @BindView(R.id.que_analysis_ly)
    LinearLayout queAnalysisLy;
    @BindView(R.id.que_analysis_all_ly)
    LinearLayout queAnalysisAllLy;
    @BindView(R.id.que_ly)
    NestedScrollView queLy;
    @BindView(R.id.que_expostion_left)
    TextView queExpostionLeft;
    @BindView(R.id.que_expostion_right)
    TextView queExpostionRight;
    @BindView(R.id.que_expostion_listView)
    RecyclerView queExpostionListView;
    @BindView(R.id.que_expostion_title)
    TextView queExpostionTitle;
    @BindView(R.id.que_expostion_min_title)
    TextView queExpostionMinTitle;
    @BindView(R.id.que_expostion_analysis)
    TextView queExpostionAnalysis;
    @BindView(R.id.que_expostion_analysis_tv)
    TextView queExpostionAnalysisTv;
    @BindView(R.id.que_expostion_left_ly)
    LinearLayout queExpostionLeftLy;
    @BindView(R.id.que_expostion_material)
    TextView queExpostionMaterial;
    @BindView(R.id.que_expostion_right_ly)
    LinearLayout queExpostionRightLy;
    @BindView(R.id.que_expostion_ly)
    LinearLayout queExpostionLy;
    @BindView(R.id.que_expostion_material_img)
    MyListView queExpostionMaterialImg;
    @BindView(R.id.que_data_text)
    TextView queDataText;
    @BindView(R.id.que_data_list)
    MyListView queDataList;
    @BindView(R.id.que_data_ly)
    LinearLayout queDataLy;
    Unbinder unbinder;
    public static QuestionsFragment instance;
    List<AppCompatRadioButton> listRadio;
    List<AppCompatCheckBox> listCheck;
    AppCompatCheckBox checkBox;
    AppCompatRadioButton appCompatRadioButton;
    ArrayList<QuestionBaseBean> result;
    AppCompatButton appCompatButton;
    private int position;
    private int answer;
    private boolean isAnalysis;
    private boolean isAnalysisOpen;
    private boolean isReportTo;
    private boolean isLeft = false;
    private int size = 3;
    private float minSize = 11;
    private float maxSize = 15;
    String date1, date2 = "";
    private ExpositionAdapter adapter;
    private PicAdapter picAdapter;

    public static QuestionsFragment newInstance(int position, boolean isAnalysis, boolean
            isAnalysisOpen, boolean isReportTo) {
        Bundle args = new Bundle();
        args.putInt("position", position);
        args.putBoolean("isAnalysis", isAnalysis);
        args.putBoolean("isAnalysisOpen", isAnalysisOpen);
        args.putBoolean("isReportTo", isReportTo);
        QuestionsFragment fragment = new QuestionsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static QuestionsFragment newInstance(int position, boolean isAnalysis, boolean isAnalysisOpen) {
        Bundle args = new Bundle();
        args.putInt("position", position);
        args.putBoolean("isAnalysis", isAnalysis);
        args.putBoolean("isAnalysisOpen", isAnalysisOpen);
        QuestionsFragment fragment = new QuestionsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_questions;
    }

    @Override
    protected void initView() {

        instance = this;
        position = getArguments().getInt("position");
        isAnalysis = getArguments().getBoolean("isAnalysis", false);
        isAnalysisOpen = getArguments().getBoolean("isAnalysisOpen", false);
        isReportTo = getArguments().getBoolean("isReportTo", false);
        listRadio = new ArrayList<>();
        listCheck = new ArrayList<>();
        struct();

        inData();
        initListner();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
        //设置布局管理器
        queExpostionListView.setLayoutManager(layoutManager);
        adapter = new ExpositionAdapter(getActivity(), result.get(position).getQuestionsContextList(), 0);
        queExpostionListView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);

        if (isAnalysis) {
            queAnalysisAllLy.setVisibility(View.VISIBLE);
            queAnalysisLy.setVisibility(View.GONE);
        } else {
            queAnalysisAllLy.setVisibility(View.GONE);
        }

        if (isAnalysisOpen && queSeeAnalysis != null) {
            showAnalysis();
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            //显示 开始计时

            // 获取当前时间
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date1 = formatter.format(currentTime);

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        size = MySharedPreferences.getInstance(getActivity()).getTextSize();
        setTitlesize(size);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setClick(MsgEvent msgEvent) {
        setTitlesize(msgEvent.getItemClick());
    }

    private void setTitlesize(int size) {
        switch (size) {
            case 1:// 小号  13  9
                minSize = 9;
                maxSize = 13;
                break;
            case 2:// 中号  14  10
                minSize = 10;
                maxSize = 14;
                break;
            case 3:// 标准  15  11
                minSize = 11;
                maxSize = 15;
                break;
            case 4:// 大号  16  12
                minSize = 12;
                maxSize = 16;
                break;
            case 5:// 巨无霸 17  13
                minSize = 13;
                maxSize = 17;
                break;
        }
        queMinTitle.setTextSize(minSize);

        queTitle.setTextSize(maxSize);
        queAnswer.setTextSize(maxSize);
        queStatistics.setTextSize(maxSize);
        queAnalysis.setTextSize(maxSize);

        queExpostionMinTitle.setTextSize(minSize);
        queExpostionTitle.setTextSize(maxSize);
        queExpostionAnalysisTv.setTextSize(maxSize);
        queExpostionMaterial.setTextSize(maxSize);
        if (!listCheck.isEmpty()) {
            for (AppCompatCheckBox b : listCheck) {
                b.setTextSize(maxSize);
            }
        }
        if (!listRadio.isEmpty()) {
            for (AppCompatRadioButton b : listRadio) {
                b.setTextSize(maxSize);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(EvenBaseBean event) {
        Log.i("yxp", event.hashCode() + "----");
        if (event.getType() == 1)
            result = event.getBaseBean();
    }

    /**
     * 设置解析内容
     */
    private void setAnalysis() {
        if (result.get(position).isFinishAnswer()) {// 完成答题
            if (result.get(position).isChooseResult()) {// 答题正确
                if (result.get(position).getQuestionsAnswerInfo().getAnswerArray().size() != 0) {
                    if (result.get(position).getQuestionTypeId().equals("10")) {
                        //单选
                        queAnswer.setText(Html.fromHtml("正确答案<font color=\'#00bf62\'>" + Helper.asciiToString(result.get(position).getRightAnswer()) + "</font><font color=\'#333333\'>，回答正确"));
                    } else if (result.get(position).getQuestionTypeId().equals("20") || result.get(position).getQuestionTypeId().equals("35")) {
                        //多选
                        String text = "";
                        for (int i = 0; i < result.get(position).getRightList().size(); i++) {
                            text += Helper.asciiToString(result.get(position).getRightList().get(i));
                        }
                        queAnswer.setText(Html.fromHtml("正确答案<font color=\'#00bf62\'>" + text + "</font><font color=\'#333333\'>，回答正确"));
                    }
                }
            } else {// 答题错误
                if (result.get(position).getQuestionsAnswerInfo().getAnswerArray().size() != 0) {
                    if (result.get(position).getQuestionTypeId().equals("10")) {
                        //单选
                        queAnswer.setText(Html.fromHtml("正确答案<font color=\'#00bf62\'>" + Helper.asciiToString(result.get(position).getRightAnswer()) + "</font><font color=\'#333333\'>，您的答案</font><font color=\'#FF6559\'>" + Helper.asciiToString(result.get(position).getErrorAnswer())));
                    } else if (result.get(position).getQuestionTypeId().equals("20") || result.get(position).getQuestionTypeId().equals("35")) {
                        //多选
                        String errortext = "";
                        for (int i = 0; i < result.get(position).getResultList().size(); i++) {
                            errortext += Helper.asciiToString(result.get(position).getResultList().get(i));
                        }
                        String text = "";
                        for (int i = 0; i < result.get(position).getRightList().size(); i++) {
                            text += Helper.asciiToString(result.get(position).getRightList().get(i));
                        }
                        queAnswer.setText(Html.fromHtml("正确答案<font color=\'#00bf62\'>" + text + "</font><font color=\'#333333\'>，您的答案</font><font color=\'#FF6559\'>" + errortext));
                    }
                }
            }

        } else {// 未答题
            if (result.get(position).getQuestionsAnswerInfo().getAnswerArray().size() != 0) {
                String c = result.get(position).getQuestionsAnswerInfo().getAnswerArray().toString().replace("[", "");
                String content = c.replace("]", "");
                queAnswer.setText(Html.fromHtml("正确答案<font color=\'#00bf62\'>" + content + "</font><font color=\'#333333\'>，本题未作答"));
            }
        }

        queStatistics.setText(Html.fromHtml("个人统计：作答本题<font color=\'#00bf62\'>" + result.get
                (position).getAnswerCount() + "</font><font color=\'#333333\'>次，做错</font><font " +
                "color=\'#ff6559\'>" + result.get(position).getAnswerErrorCount() + "</font>次"));
        queAnalysis.setText(Html.fromHtml(result.get(position).getQuestionsAnswerInfo()
                .getFormatContent(), imgGetter, null));
    }

    private void inData() {
        // 遍历资料 并判断 ContextQuestionId是否跟资料的ContextId相等  相等显示资料部分
        for (int context = 0; context < result.get(position).getQuestionsContextList().size(); context++) {
            if (result.get(position).getContextQuestionId().equals(result.get(position).getQuestionsContextList().get(context).getContextId())) {
                queDataLy.setVisibility(View.VISIBLE);
                String data = result.get(position).getQuestionsContextList().get(context).getFormatContent().replace("[", "");
                String dataContent = data.replace("]", "");
                queDataText.setText(Html.fromHtml(dataContent, imgGetter, null));
                PicAdapter adapter = new PicAdapter(getActivity(), result.get(position).getQuestionsContextList().get(context).getFormatImages());
                queDataList.setAdapter(adapter);
                break;
            } else {
                queDataLy.setVisibility(View.GONE);
            }
        }

        String t = result.get(position).getFormatContent().replace("<p>", "");
        String title = t.replace("</p>", "");
        if (result.get(position).getQuestionTypeId().equals("50")) {// 材料主观题题
            queLy.setVisibility(View.GONE);
            queExpostionLy.setVisibility(View.VISIBLE);
            queExpostionLeft.performClick();
            queExpostionTitle.setText(Html.fromHtml(title, imgGetter, null));  // 标题
            queExpostionMinTitle.setText("(" + result.get(position).getRealPaperTitle() + ")");// 小标题
            queExpostionAnalysisTv.setText("参考答案\n" + Html.fromHtml(result.get(position).getQuestionsAnswerInfo().getAnswerArray().get(0).toString(), imgGetter, null));
            if (result.get(position).getQuestionsContextList() != null && result.get(position).getQuestionsContextList().size() != 0) {
                queExpostionMaterial.setText(Html.fromHtml(result.get(position).getQuestionsContextList().get(0).getFormatContent(), imgGetter, null));
                if (result.get(position).getQuestionsContextList().get(0).getFormatImages() != null && result.get(position).getQuestionsContextList().get(0).getFormatImages().size() != 0) {
                    // 设置图片
                    queExpostionMaterialImg.setVisibility(View.VISIBLE);
                    picAdapter = new PicAdapter(getActivity(), result.get(position).getQuestionsContextList().get(0).getFormatImages());
                    queExpostionMaterialImg.setAdapter(picAdapter);
                } else {
                    queExpostionMaterialImg.setVisibility(View.GONE);
                }
            }
        } else {
            queLy.setVisibility(View.VISIBLE);
            queExpostionLy.setVisibility(View.GONE);
            queTitle.setText(Html.fromHtml(title, imgGetter, null));  // 标题
            queMinTitle.setText("(" + result.get(position).getRealPaperTitle() + ")");// 小标题

            //多选
            // initCheckBox();
            if (result.get(position).getQuestionTypeId().equals("10")) { //单选
                answer = Helper.stringToAscii(result.get(position).getQuestionsAnswerInfo().getAnswerArray().get(0).toString());
                //单选
                initRadioButton();

            }

            if (result.get(position).getQuestionTypeId().equals("20") || result.get(position).getQuestionTypeId().equals("35")) { //多选

                //多选
                initCheckBox();
            }
        }

        //显示图片
        if (result.get(position).getFormatImages().size() == 0)
            queImg.setVisibility(View.GONE);

        else {
            String url = "";
            for (int i = 0; i < result.get(position).getFormatImages().size(); i++) {
                url = result.get(position).getFormatImages().get(i).toString();


            }
            Picasso.with(getContext()).load(url).placeholder(R.drawable.loading).into(queImg);
        }

    }

    private void initRadioButton() {
        for (int i = 0; i < result.get(position).getQuestioncontentList().size(); i++) {
            if (!TextUtils.isEmpty(result.get(position).getQuestioncontentList().get(i)
                    .getSelectValue())) {
                addRadioButtonView("   " + result.get(position).getQuestioncontentList().get(i).getSelectValue(), i);
            }
        }

        if (result.get(position).isFinishAnswer()) {//判断当前题目是否已经答题答过了，如果是的话，就恢复答题数据，并且设置不可点击

            radioButtonClickEnable();

            try {
                if (!result.get(position).isChooseResult()) {
                    //如果没有选择到正确答案的话，就要显示错误答案，否则不显示
                    AppCompatRadioButton radio = listRadio.get(result.get(position)
                            .getErrorAnswer() - 1);
                    radio.setTextColor(getContext().getResources().getColor(R.color.aff6559));
                    setErrorDrable(radio);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                AppCompatRadioButton radio = listRadio.get(result.get(position).getRightAnswer() - 1);
                radio.setTextColor(getContext().getResources().getColor(R.color.a00BF62));
                setRightDrable(radio);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //多选题
    private void initCheckBox() {

        for (int i = 0; i < result.get(position).getQuestioncontentList().size(); i++) {
            if (!TextUtils.isEmpty(result.get(position).getQuestioncontentList().get(i).getSelectValue())) {
                addCheckBoxView("   " + result.get(position).getQuestioncontentList().get(i).getSelectValue(), i);
            }
        }


        for (int i = 0; i < listCheck.size(); i++) {
            final int finalI = i;
            listCheck.get(i).setOnCheckedChangeListener(new CompoundButton
                    .OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {


                    if (b) {
                        listCheck.get(finalI).setTextColor(getContext().getResources().getColor(R.color.aff6559));
                        listCheck.get(finalI).setButtonDrawable(setHong(finalI));//设置样式
                    } else {
                        listCheck.get(finalI).setTextColor(getContext().getResources().getColor(R.color.a333333));
                        listCheck.get(finalI).setButtonDrawable(setBai(finalI));//设置样式
                        appCompatButton.setBackgroundColor(getContext().getResources().getColor(R.color.hint));
                        appCompatButton.setEnabled(false);
                    }

                    for (int c = 0; c < listCheck.size(); c++) {
                        if (listCheck.get(c).isChecked()) {
                            appCompatButton.setBackgroundColor(getContext().getResources().getColor(R.color.aff6559));
                            appCompatButton.setEnabled(true);
                        }
                    }
                }
            });
        }


        if (Constant.title_tv.equals("7") || Constant.title_tv.equals("8") || Constant.title_tv.equals("5")) {
            //错题练习 与收藏 不可点击

            checkBoxClickEnable();//多选不可点击
        } else {
            if (isReportTo) {
                checkBoxClickEnable();
                //遍历用户的选择
                for (int i = 0; i < result.get(position).getResultList().size(); i++) {
                    int a = result.get(position).getResultList().get(i);//拿到答题的标号
                    listCheck.get(a - 1).setTextColor(getContext().getResources().getColor(R.color.aff6559));
                    listCheck.get(a - 1).setChecked(true);
                    setErrorChecBox(listCheck.get(a - 1));//设置样式
                }

                for (int i = 0; i < result.get(position).getRightList().size(); i++) {
                    int a = result.get(position).getRightList().get(i);//拿到答题的标号
                    listCheck.get(a - 1).setTextColor(getContext().getResources().getColor(R.color.a00BF62));
                    setRightChecbox(listCheck.get(a - 1));//设置样式
                }
            }

            if (result.get(position).isFinishAnswer()) { //已答完题目
                checkBoxClickEnable();//多选不可点击
                //遍历用户的选择
                for (int i = 0; i < result.get(position).getResultList().size(); i++) {
                    int a = result.get(position).getResultList().get(i);//拿到答题的标号
                    listCheck.get(a - 1).setTextColor(getContext().getResources().getColor(R.color.aff6559));
                    listCheck.get(a - 1).setChecked(true);
                    setErrorChecBox(listCheck.get(a - 1));//设置样式
                }

                for (int i = 0; i < result.get(position).getRightList().size(); i++) {
                    int a = result.get(position).getRightList().get(i);//拿到答题的标号
                    listCheck.get(a - 1).setTextColor(getContext().getResources().getColor(R.color.a00BF62));
                    setRightChecbox(listCheck.get(a - 1));//设置样式
                }


            } else {
                //添加一个确定按钮
                if (isReportTo) {
                    return;
                }
                appCompatButton = new AppCompatButton(getContext());
                appCompatButton.setText("确定");
                appCompatButton.setEnabled(false);
                appCompatButton.setBackgroundColor(getContext().getResources().getColor(R.color.hint));
                appCompatButton.setTextColor(Color.parseColor("#ffffff"));
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                params.setMargins(20, 30, 20, 20);
                appCompatButton.setLayoutParams(params);
                appCompatButton.setVisibility(View.VISIBLE);
                queCheckLayout.addView(appCompatButton);
                appCompatButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                    doHandle();

                        //然后进行筛选
                        commonJudge();
                    }
                });
            }
        }
    }

    Html.ImageGetter imgGetter = new Html.ImageGetter() {
        public Drawable getDrawable(String source) {
            Drawable drawable = null;
            URL url;
            try {
                url = new URL(source);
                drawable = Drawable.createFromStream(url.openStream(), ""); // 获取网路图片
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() + 50, drawable.getIntrinsicHeight() + 50);
            return drawable;
        }
    };

    public static void struct() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects() // 探测SQLite数据库操作
                .penaltyLog() // 打印logcat
                .penaltyDeath().build());
    }

    private Drawable setBai(int i) {
        Drawable bitmapDrawable = null;
        if (i == 0) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_a_ic);
        }
        if (i == 1) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_b_ic);
        }
        if (i == 2) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_c_ic);
        }
        if (i == 3) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_d_ic);
        }

        if (i == 4) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_e_ic);
        }
        if (i == 5) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_f_ic);
        }
        if (i == 6) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_g_ic);
        }
        if (i == 7) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_h_ic);
        }
        return bitmapDrawable;
    }

    private Drawable setHong(int i) {
        Drawable bitmapDrawable = null;
        if (i == 0) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_ahong_ic);
        }
        if (i == 1) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_bfang_ic);
        }
        if (i == 2) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_cfang_ic);
        }
        if (i == 3) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_dfang_ic);
        }


        if (i == 4) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_he_ic);
        }
        if (i == 5) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_hf_ic);
        }
        if (i == 6) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_hg_ic);
        }
        if (i == 7) {
            bitmapDrawable = getResources().getDrawable(R.mipmap.home_hh_ic);
        }
        return bitmapDrawable;
    }

    public void addCheckBoxView(String question, int i) {
        checkBox = new AppCompatCheckBox(getContext());
        checkBox.setGravity(Gravity.CENTER_VERTICAL);
        checkBox.setText(Html.fromHtml(question, imgGetter, null));
        checkBox.setTextSize(maxSize);
        checkBox.setTextColor(getContext().getResources().getColor(R.color.black333));

        checkBox.setButtonDrawable(setBai(i));
        checkBox.setPadding(20, 0, 0, 0);
        RadioGroup.LayoutParams param = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT);
        param.setMargins(10, 20, 10, 10);
        checkBox.setLayoutParams(param);
        queCheckLayout.addView(checkBox);
        listCheck.add(checkBox);
    }


    public void addRadioButtonView(String question, int i) {
        appCompatRadioButton = new AppCompatRadioButton(getContext());
        appCompatRadioButton.setGravity(Gravity.CENTER_VERTICAL);
        appCompatRadioButton.setText(Html.fromHtml(question, imgGetter, null));

        appCompatRadioButton.setButtonDrawable(setBai(i));
        appCompatRadioButton.setTextSize(maxSize);
        appCompatRadioButton.setPadding(20, 0, 0, 0);
        appCompatRadioButton.setTextColor(getContext().getResources().getColor(R.color.black333));
        RadioGroup.LayoutParams param = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT);
        param.setMargins(10, 20, 10, 10);
        appCompatRadioButton.setLayoutParams(param);
        queGroup.addView(appCompatRadioButton);


        listRadio.add(appCompatRadioButton);
    }


    public void setErrorDrable(AppCompatRadioButton appCompatRadioButton) {
        Drawable bitmapDrawable = (Drawable) getResources().getDrawable(R.mipmap.home_cuo_ic);
        appCompatRadioButton.setButtonDrawable(bitmapDrawable);
    }

    public void setErrorChecBox(AppCompatCheckBox appCompatRadioButton) {
        Drawable bitmapDrawable = (Drawable) getResources().getDrawable(R.mipmap.home_cuo_ic);
        appCompatRadioButton.setButtonDrawable(bitmapDrawable);
    }


    public void setRightDrable(AppCompatRadioButton appCompatRadioButton) {
        Drawable bitmapDrawable = (Drawable) getResources().getDrawable(R.mipmap.home_dui_ic);
        appCompatRadioButton.setButtonDrawable(bitmapDrawable);
    }

    public void setRightChecbox(AppCompatCheckBox appCompatRadioButton) {
        Drawable bitmapDrawable = (Drawable) getResources().getDrawable(R.mipmap.home_dui_ic);
        appCompatRadioButton.setButtonDrawable(bitmapDrawable);
    }

    void radioButtonClickEnable() {
        for (AppCompatRadioButton radioButton :
                listRadio) {
            radioButton.setClickable(false);
        }
    }

    void checkBoxClickEnable() {
        for (AppCompatCheckBox checkbos :
                listCheck) {
            checkbos.setClickable(false);
        }
    }

    void commonJudge() {

        result.get(position).getResultList().clear();
        //存储用户选择的答案
        for (int i = 0; i < listCheck.size(); i++) {
            if (listCheck.get(i).isChecked()) {  //遍历查询当前是否选中
                result.get(position).getResultList().add(i + 1);
                System.out.println("本体选择的答案是===" + "123==" + (i + 1));
            }
        }
        System.out.println("本体选择的答案是===" + "1236==" + result.get(position).getResultList()
                .toString());

        if (Constant.title_tv.equals("3") || Constant.title_tv.equals("4")) {
            if (Helper.equalList(result.get(position).getRightList(), result.get(position).getResultList())) {
                result.get(position).setChooseResult(true);
            } else {

                //记录错误
                result.get(position).setChooseResult(false);
            }


            new Handler().postDelayed(new Runnable() {
                public void run() {
                    //execute the task
                    if (getActivity() instanceof QuestionTestActivity) {
                        QuestionTestActivity.nextQuestion();
                    } else if (getActivity() instanceof Error_Analysis_Activity) {
                        Error_Analysis_Activity.nextQuestion();
                    }
                }
            }, 300);
        } else {
            //不是 3  和 4 的情况下

            //先判断用户输入的和答案的选择个数是否相同
            if (Helper.equalList(result.get(position).getRightList(), result.get(position).getResultList())) {
                //选择正确
                result.get(position).setChooseResult(true);
                for (int l = 0; l < listCheck.size(); l++) {
                    // 设置状态
                    setRightChecbox(listCheck.get(l));//设置样式
                    listCheck.get(l).setTextColor(getContext().getResources().getColor(R
                            .color.a00BF62));
                    result.get(position).getRightList().add(l);

                    break;
                }


            } else {
                //选择错误
                result.get(position).setChooseResult(false);
                //如果有错误的话就把错误答案显示出来
                for (int j = 0; j < listCheck.size(); j++) {
                    if (listCheck.get(j).isChecked()) {  //遍历查询当前是否选中
                        listCheck.get(j).setTextColor(getContext().getResources().getColor(R.color.aff6559));
                        setErrorChecBox(listCheck.get(j));//设置样式
                    }
                }
                for (int i = 0; i < result.get(position).getRightList().size(); i++) {
                    listCheck.get(result.get(position).getRightList().get(i) - 1).setTextColor(getContext().getResources().getColor(R.color.a00BF62));
                    setRightChecbox(listCheck.get(result.get(position).getRightList().get(i) - 1));
                }
            }


            queSeeAnalysis.setVisibility(View.GONE);
            queAnalysisLy.setVisibility(View.VISIBLE);

        }

        result.get(position).setFinishAnswer(true);
        setAnalysis();
        result.get(position).setQuestiontime((int) gettime());//获取每道题答题时间
        if (Constant.title_tv.equals("3") || Constant.title_tv.equals("4")) {

        } else {
            checkBoxClickEnable();//多选不可点击
            if (appCompatButton != null) {
                appCompatButton.setVisibility(View.INVISIBLE);
            }
        }

        if (getActivity() instanceof QuestionTestActivity) {
            QuestionTestActivity.upDataRightAndError();
        } else if (getActivity() instanceof Error_Analysis_Activity) {
            Error_Analysis_Activity.upDataRightAndError();
        }
    }

    private void initListner() {
        queGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup rd, int id) {
                if (Constant.title_tv.equals("7") || Constant.title_tv.equals("8") || Constant.title_tv.equals("5")) {
                    //错题练习 与收藏 不可点击
                    radioButtonClickEnable();//设置不可点击
                } else {

                    for (int i = 0; i < listRadio.size(); i++) {
                        AppCompatRadioButton radioButton = listRadio.get(i);

                        if (Constant.title_tv.equals("3") || Constant.title_tv.equals("4")) {
                            //设置样式
                            radioButton.setButtonDrawable(setBai(i));
                            radioButton.setTextColor(getContext().getResources().getColor(R.color.black333));
                        }

                    }

                    for (int i = 0; i < listRadio.size(); i++) {
                        AppCompatRadioButton radioButton = listRadio.get(i);
                        //遍历查找找到当前点击的item

                        if (radioButton.getId() == id) {

                            if ((i + 1) == answer) { //判断选择是否是正确答案
                                System.out.println("用户选择的答案是正确答案===" + (i + 1));

                                if (Constant.title_tv.equals("3") || Constant.title_tv.equals("4")) {
                                    radioButton.setButtonDrawable(setHong(i));
                                    radioButton.setTextColor(getContext().getResources().getColor(R.color.aff6559));

                                } else {
                                    radioButton.setTextColor(getContext().getResources().getColor(R.color.a00BF62));
                                    setRightDrable(radioButton);//设置样式
                                }

                                result.get(position).setRightAnswer(i + 1);//设置用户答对的是什么答案
                                result.get(position).setChooseResult(true);//存储用户选择的答案为正确的

                                result.get(position).setQuestiontime((int) gettime());//获取每道题答题时间


                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        //execute the task
                                        if (getActivity() instanceof QuestionTestActivity) {
                                            QuestionTestActivity.nextQuestion();
                                        } else if (getActivity() instanceof Error_Analysis_Activity) {
                                            Error_Analysis_Activity.nextQuestion();
                                        }
                                    }
                                }, 300);

                                if ((position + 1) == result.size()) { //当为最后一题并且答对 则跳转到答题卡
                                    System.out.println("跳转到答题卡===");
                                    EventBus.getDefault().postSticky(result);
                                    Intent intent = new Intent(getActivity(), AnswerCardActivity.class);
                                    startActivity(intent);
                                }


                            } else {//选择的是错误答案
                                System.out.println("用户选择的答案是错误答案===" + (i + 1));

                                if (Constant.title_tv.equals("3") || Constant.title_tv.equals("4")) { //针对 真题与巩固

                                    radioButton.setTextColor(getContext().getResources().getColor(R.color.aff6559));
                                    radioButton.setButtonDrawable(setHong(i));
                                    result.get(position).setErrorAnswer(i + 1);//设置选错题目的标识
                                    // 用户答错的是什么答案
                                    result.get(position).setChooseResult(false);//存储用户选择的答案为错误的
                                    result.get(position).setQuestiontime((int) gettime());
                                    //获取每道题答题时间
                                    new Handler().postDelayed(new Runnable() {
                                        public void run() {
                                            //execute the task
                                            if (getActivity() instanceof QuestionTestActivity) {
                                                QuestionTestActivity.nextQuestion();
                                            } else if (getActivity() instanceof Error_Analysis_Activity) {
                                                Error_Analysis_Activity.nextQuestion();
                                            }
                                        }
                                    }, 300);

                                } else {
                                    //其余的可以展开查看解释
                                    try {
                                        result.get(position).setQuestiontime((int) gettime());
                                        //获取每道题答题时间
                                        radioButton.setTextColor(getContext().getResources().getColor(R.color.aff6559));
                                        setErrorDrable(radioButton);//设置样式

                                        listRadio.get(answer - 1).setTextColor(getContext().getResources().getColor(R.color.a00BF62));
                                        setRightDrable(listRadio.get(answer - 1));

                                        result.get(position).setErrorAnswer(i + 1);//设置选错题目的标识
                                        // 用户答错的是什么答案
                                        result.get(position).setChooseResult(false);//存储用户选择的答案为错误的


                                        queSeeAnalysis.setVisibility(View.GONE);
                                        queAnalysisLy.setVisibility(View.VISIBLE);
                                    } catch (ArrayIndexOutOfBoundsException e) {
                                        System.out.println("数组越界！");
                                        e.printStackTrace();
                                    }
                                }

                            }
                            result.get(position).setRightAnswer(answer);//设置选对题目的标识 用户答对的是什么答案
                            result.get(position).setFinishAnswer(true);//设置完成了答题
                            setAnalysis();

                            if (Constant.title_tv.equals("3") || Constant.title_tv.equals("4")) {

                            } else {
                                radioButtonClickEnable();//设置不可点击
                            }
                            if (getActivity() instanceof QuestionTestActivity) {
                                QuestionTestActivity.upDataRightAndError();//更新MainActivity
                            } else if (getActivity() instanceof Error_Analysis_Activity) {
                                Error_Analysis_Activity.upDataRightAndError();//更新MainActivity
                            }
                            break;
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void addOnClick() {

    }

    public long gettime() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date2 = formatter.format(currentTime);

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("答完答题时间====" + date2);
        long second = 0;
        try {
            Date d1 = df.parse(date1);
            Date d2 = df.parse(date2);
            long diff = d2.getTime() - d1.getTime();// 这样得到的差值是微秒级别


            long days = diff / (1000 * 60 * 60 * 24);
            long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            second = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000);
            System.out.println("本题答题时间====" + second + "秒");

        } catch (Exception e) {
        }

        return second;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        EventBus.getDefault().register(this);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    private void showAnalysis() {
        queSeeAnalysis.setVisibility(View.GONE);
        queAnalysisLy.setVisibility(View.VISIBLE);
        setAnalysis();
        if (Constant.title_tv.equals("1") || Constant.title_tv.equals("2")) {
            // 1  和  2 点击解释
            // 自动默认设置为正确答案 并且 有答题
            if (result.get(position).getQuestionTypeId().equals("10")) {
                //单选
                for (int i = 0; i < listRadio.size(); i++) {
                    AppCompatRadioButton radioButton = listRadio.get(i);
                    //遍历查找找到当前点击的item
                    if ((i + 1) == answer) {
                        //判断选择是否是正确答案
                        radioButton.setTextColor(getContext().getResources().getColor(R.color.a00BF62));
                        //设置样式
                        setRightDrable(radioButton);
                        //设置用户答对的是什么答案
                        result.get(position).setRightAnswer(i + 1);
                        //存储用户选择的答案为正确的
                        result.get(position).setChooseResult(true);
                    }
                    //设置不可点击
                    radioButtonClickEnable();
                }
            }

            if (result.get(position).getQuestionTypeId().equals("20") || result.get(position).getQuestionTypeId().equals("35")) { //多选
                if (appCompatButton != null) {
                    appCompatButton.setVisibility(View.INVISIBLE);
                }

                for (int r = 0; r < result.get(position).getRightList().size(); r++) {
                    for (int l = 0; l < listCheck.size(); l++) {
                        if (result.get(position).getRightList().get(r) == l + 1) {
                            // 设置状态
                            setRightChecbox(listCheck.get(l));//设置样式
                            listCheck.get(l).setTextColor(getContext().getResources().getColor(R.color.a00BF62));
                            result.get(position).getResultList().add(l + 1);
                            break;
                        }
                    }
                }
            }

            result.get(position).setFinishAnswer(true);//设置完成了答题
            result.get(position).setQuestiontime((int) gettime());//获取每道题答题时间
        }

        if (Constant.title_tv.equals("7") || Constant.title_tv.equals("8") || Constant.title_tv.equals("5")) {
            if (result.get(position).getQuestionTypeId().equals("10")) { //单选
                for (int i = 0; i < listRadio.size(); i++) {
                    AppCompatRadioButton radioButton = listRadio.get(i);
                    //遍历查找找到当前点击的item
                    if ((i + 1) == answer) {//判断选择是否是正确答案
                        //System.out.println("用户选择的答案是正确答案===" + (i + 1));
                        radioButton.setTextColor(getContext().getResources().getColor(R.color.a00BF62));
                        setRightDrable(radioButton);//设置样式
                    }
                    radioButtonClickEnable();//设置不可点击
                }
            }

            if (result.get(position).getQuestionTypeId().equals("20") || result.get(position).getQuestionTypeId().equals("35")) { //多选
                //先判断用户输入的和答案的选择个数是否相同
                for (int r = 0; r < result.get(position).getRightList().size(); r++) {
                    for (int l = 0; l < listCheck.size(); l++) {
                        if (result.get(position).getRightList().get(r) == l + 1) {
                            // 设置状态

                            setRightChecbox(listCheck.get(l));//设置样式
                            listCheck.get(l).setTextColor(getContext().getResources().getColor(R.color.a00BF62));

                            break;
                        }
                    }
                }
            }
        }
    }

    @OnClick({R.id.que_see_analysis, R.id.que_expostion_left, R.id.que_expostion_right, R.id.que_expostion_analysis})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.que_see_analysis:
                showAnalysis();
                break;
            case R.id.que_expostion_left:
                if (isLeft) {
                    return;
                }
                queExpostionLeft.setTextColor(getActivity().getResources().getColor(R.color.aff6559));
                queExpostionRight.setTextColor(getActivity().getResources().getColor(R.color.a333333));
                isLeft = true;
                queExpostionLeftLy.setVisibility(View.VISIBLE);
                queExpostionListView.setVisibility(View.GONE);
                queExpostionRightLy.setVisibility(View.GONE);
                break;
            case R.id.que_expostion_right:
                if (!isLeft) {
                    return;
                }
                queExpostionLeft.setTextColor(getActivity().getResources().getColor(R.color.a333333));
                queExpostionRight.setTextColor(getActivity().getResources().getColor(R.color.aff6559));
                isLeft = false;
                queExpostionLeftLy.setVisibility(View.GONE);
                queExpostionListView.setVisibility(View.VISIBLE);
                queExpostionRightLy.setVisibility(View.VISIBLE);
                break;
            case R.id.que_expostion_analysis:
                queExpostionAnalysis.setVisibility(View.INVISIBLE);
                queExpostionAnalysisTv.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onItemClick(int pos) {
        queExpostionMaterial.setText(Html.fromHtml(result.get(position).getQuestionsContextList().get(pos).getFormatContent()));
        adapter.notifyDataSetChanged();
        if (result.get(position).getQuestionsContextList().get(0).getFormatImages() != null && result.get(position).getQuestionsContextList().get(pos).getFormatImages().size() != 0) {
            // 设置图片
            queExpostionMaterialImg.setVisibility(View.VISIBLE);
            picAdapter.setData(result.get(position).getQuestionsContextList().get(pos).getFormatImages());
            picAdapter.notifyDataSetChanged();
        } else {
            queExpostionMaterialImg.setVisibility(View.GONE);
        }
    }
}
